import React, { Component, Suspense } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import PageLoading from '@/components/PageLoading';
import { FormattedMessage } from 'umi-plugin-react/locale';
import {
  Row,
  Col,
  Card,
  Icon,
  Tooltip,
  Form,
  Button,
  Progress,
  Tabs,
  Select,
  Input,
  Table,
  Spin,
  Checkbox,
  Radio,
  message,
} from 'antd';
import styles from './similarAsk.less';
import bulb from '@/assets/medicalKnowledge/灯泡.png';
import { faTshirt } from '@fortawesome/fontawesome-free-solid';
import StandardToAsk from './standardToAsk';

const { Option } = Select;
const Search = Input.Search;

class SimilarAsk extends Component {
  constructor(props) {
    super(props);
    this.state = {
      ProgressName: '',
      totala: '',
      Selectpd: 'false', // false 为未忽略 true 为已忽略
      Selectcc: false, // 是否忽略传参
      login: false,
      logines: false,
      searchKeys: '',
      page: 1,
      pageSize: 10,
      index: '',
      index: '',
      similarList: [],
      qaId: '',
      question: '',
      value: '',
      value1: '',
      judgeMobile: '',
      judgeMobiles: '',
      frompd: 1,
      selected: '',
    };
  }

  componentDidMount() {
    const { Selectcc, pageSize, page, searchKeys } = this.state;
    this.similarAskList(Selectcc, pageSize, page, searchKeys);
  }

  componentDidUpdate() {}

  componentWillReceiveProps(nextProps, nextContext) {
    if (nextProps.ProgressName !== this.state.ProgressName) {
      this.setState({ ProgressName: nextProps.ProgressName });
    }
    if (nextProps.ProgressName == 2) {
      // 列表清空
      this.setState({
        Selectpd: 'false',
        similarList: [],
        ProgressName: nextProps.ProgressName,
        totala: 0,
      });
      this.props.totala1(0);
    };
    if (nextProps.ProgressName == 1) {
      // 恢复数据
      if (this.state.ProgressName !== nextProps.ProgressName) {
        this.setState({ page: 1, pageSize: 10, searchKeys: '' }, () => {
          const { Selectcc, pageSize, page, searchKeys } = this.state;
          this.similarAskList(Selectcc, pageSize, page, searchKeys);
        });
        this.props.totala1(this.state.totala);
        this.setState({ ProgressName: nextProps.ProgressName });
      }
    }
  }

  SelectValue = value => {
    if (value === 'false') {
      this.setState({ Selectcc: false }, () => {
        const { Selectcc, pageSize, page, searchKeys } = this.state;
        this.similarAskList(Selectcc, pageSize, page, searchKeys);
      });
    }
    if (value === 'true') {
      this.setState({ Selectcc: true }, () => {
        const { Selectcc, pageSize, page, searchKeys } = this.state;
        this.similarAskList(Selectcc, pageSize, page, searchKeys);
      });
    }
  };

  appendes = item => {
    const { value, value1, index, index1, qaId, question } = this.state;
    if (item.types[index] == 1) {
      this.StandardToAsk.openModal('appendSimilarToAsk', {
        ...item,
        qaId: item.qaIds[index],
        sQaId: item.qaIds[index1],
        question,
      });
    } else {
      this.append(item, item.qaIds[index], item.qaIds[index1], question, undefined);
    }
  };

  append = (item, qaId, sQaId, question, sQuestion) => {
    const { value, value1, judgeMobile, judgeMobiles } = this.state;
    if (
      judgeMobile === item.set[0] ||
      judgeMobile === item.set[1] ||
      judgeMobiles === item.set[0] ||
      judgeMobiles === item.set[1]
    ) {
      this.setState({ login: true });
      const { dispatch, currentUser } = this.props;
      this.reqRef = requestAnimationFrame(() => {
        this.setState({ login: false });
        dispatch({
          type: 'medicalKnowledge/movingSimilarQuestions',
          payload: {
            id: item.id,
            qaId: qaId,
            sQaId: sQaId,
            question: question,
            sQuestion: sQuestion,
          },
          callback: res => {
            if (res.data) {
              this.StandardToAsk.cancelModal();
              message.success(`${res.msg}`);
            };
            this.setState({ login: false, value: '', value1: '' }, () => {
              const { Selectcc, pageSize, page, searchKeys } = this.state;
              this.similarAskList(Selectcc, pageSize, page, searchKeys); // 刷新页面
            });
          },
        });
      });
    } else {
      message.error('无效的移动操作');
    }
  };

  anButton = (item, idIndex) => {
    // 相似问;
    this.setState({ judgeMobile: idIndex });
  };

  anButtons = (item, idIndex) => {
    // 所属知识点;
    this.setState({ judgeMobiles: idIndex });
  };

  delSimilarAsk = (items, item, index) => {
    // 删除相似问;
    this.setState({ login: true });
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'medicalKnowledge/deleteSimilarQuestions',
        payload: { question: item, qaId: items.qaIds[index], id: items.id },
        callback: res => {
          if (res.data) {
            this.StandardToAsk.cancelModal();
            message.success(`${res.msg}`);
          };
          this.setState({ login: false, }, () => {
            const { Selectcc, pageSize, page, searchKeys } = this.state;
            this.similarAskList(Selectcc, pageSize, page, searchKeys);
          });
        },
      });
    });
  };

  deleteTable = (items, item, index) => {
    if (items.types[index] == 1) {
      this.StandardToAsk.openModal('delSimilarToAsk', { items, item, index });
    } else {
      this.delSimilarAsk(items, item, index);
    }
  };

  iose = item => {
    const { Selectcc } = this.state;
    if (Selectcc) {
      this.ignore(0, item.id);
    };
    if (Selectcc === false) {
      this.ignore(1, item.id);
    };
  };

  ignore = (a, b) => {
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'medicalKnowledge/ignoreSimilarQue',
        payload: { ignore: a, id: b },
        callback: res => {
          if (res.statue === 'success') {
            message.success(`${res.msg}`);
          };
          this.setState({ login: false, }, () => {
            const { Selectcc, pageSize, page, searchKeys } = this.state;
            this.similarAskList(Selectcc, pageSize, page, searchKeys);
          });
        },
      });
    });
  };

  onChangeCheckbox = checkedValues => {};

  onChangeGroup = (e, items, index, inIndex) => {
    if (e.target.value === items.set[0]) {
      this.setState({
        value: inIndex,
        selected: 1,
        value1: items.set[1],
        qaId: items.qaIds[1],
        question: items.questions[index],
        index: index,
        index1: 1,
      });
    }
    if (e.target.value === items.set[1]) {
      this.setState({
        value: inIndex,
        selected: 2,
        value1: items.set[0],
        qaId: items.qaIds[0],
        question: items.questions[index],
        index: index,
        index1: 0,
      });
    }
  };

  onChangeIntellectual = (e, items, index, inIndex) => {
    if (e.target.value === items.set[0]) {
      this.setState({
        value1: inIndex,
        selected: 1,
        value: items.set[1],
        qaId: items.qaIds[index],
        question: items.questions[1],
        index1: index,
        index: 1,
      });
    }
    if (e.target.value === items.set[1]) {
      this.setState({
        value1: inIndex,
        selected: 2,
        value: items.set[0],
        qaId: items.qaIds[index],
        question: items.questions[0],
        index1: index,
        index: 0,
      });
    }
  };

  // 相似问列表
  similarAskList = (isIgnore, limit = 10, page = 1, searchKeys) => {
    this.setState({ login: true });
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'medicalKnowledge/similarAskList',
        payload: {
          isIgnore: isIgnore ? 1 : 0,
          size: limit,
          current: page,
          questions: searchKeys,
          tenantId: currentUser.tenantId,
        },
        callback: res => {
          let Data = res.records;
          Data.map((item, index) => {
            let a = [];
            item.qaIds.map((val, indx) => {
              let b = `${val}${index}`;
              a.push(b);
            });
            Data[index].set = a;
          });
          this.setState({ login: false, similarList: Data, totala: res.total, }, () => {
            this.props.totala1(this.state.totala);
          });
        },
      });
    });
  };

  pageWay = a => {
    this.setState({ page: a }, () => {
      const { Selectcc, pageSize, page, searchKeys } = this.state;
      this.similarAskList(Selectcc, pageSize, page, searchKeys);
    });
  };

  onShowSizepageWay = (a, b) => {
    this.setState({ page: a, pageSize: b }, () => {
      const { Selectcc, pageSize, page, searchKeys } = this.state;
      this.similarAskList(Selectcc, pageSize, page, searchKeys);
    });
  };

  allIgnore = () => {
    this.setState({ logines: true, }, () => {
      // 全部忽略
      const { Selectcc } = this.state;
      if (Selectcc) {
        this.ignoreAll(0);
      };
      if (Selectcc === false) {
        this.ignoreAll(1);
      };
    });
  };

  ignoreAll = a => {
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'medicalKnowledge/allIgnoreSimilarQue',
        payload: { ignore: a },
        callback: res => {
          if (res.statue === 'success') {
            message.success(`${res.msg}`);
          };
          this.setState({ login: false, logines: false, }, () => {
            const { Selectcc, pageSize, page, searchKeys } = this.state;
            this.similarAskList(Selectcc, pageSize, page, searchKeys);
          });
        },
      });
    });
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const columns = [
      {
        title: '相似问法',
        width: 'calc(30vw)',
        dataIndex: 'questions',
        render: (questions, items) => {
          return (
            <Row>
              {questions.map((item, index) => {
                return (
                  <Row style={{ marginBottom: 10 }}>
                    <Col
                      span={4}
                      onClick={() => {
                        this.anButton(item, items.set[index]);
                      }}
                    >
                      <Radio.Group
                        onChange={event => {
                          this.onChangeGroup(event, items, index, items.set[index]);
                        }}
                        value={this.state.value}
                      >
                        <Radio style={{ marginRight: 30 }} value={items.set[index]}></Radio>
                      </Radio.Group>
                    </Col>
                    <Col span={16}>
                      <div dangerouslySetInnerHTML={{ __html: item }}></div>
                    </Col>
                    <Col span={4}>
                      <Icon
                        onClick={() => {
                          this.deleteTable(items, item, index);
                        }}
                        style={{ fontSize: 16, color: '#9e9e9e', marginLeft: 20 }}
                        type="close-circle"
                      />
                    </Col>
                  </Row>
                );
              })}
            </Row>
          );
        },
      },
      {
        title: '',
        width: 'calc(10vw)',
        dataIndex: '',
        render: (text, item) => {
          return (
            <div className="zdyButtonD">
              <Button
                onClick={text => {
                  // this.append(item);
                  this.appendes(item);
                }}
                type="primary"
              >
                {'添加到>>'}
              </Button>
            </div>
          );
        },
      },
      {
        title: '所属知识点',
        dataIndex: 'stQuestions',
        width: 'calc(30vw)',
        render: (stQuestions, items) => {
          return (
            <Row>
              {stQuestions.map((item, index) => {
                return (
                  <Row style={{ marginBottom: 10 }}>
                    <Col
                      span={4}
                      onClick={() => {
                        this.anButtons(item, items.set[index]);
                      }}
                    >
                      <Radio.Group
                        onChange={event => {
                          this.onChangeIntellectual(event, items, index, items.set[index]);
                        }}
                        value={this.state.value1}
                      >
                        <Radio style={{ marginRight: 30 }} value={items.set[index]}></Radio>
                      </Radio.Group>
                    </Col>
                    <Col span={20}>{item}</Col>
                  </Row>
                );
              })}
            </Row>
          );
        },
      },
      {
        title: '',
        width: 'calc(10vw)',
        dataIndex: '',
        render: (text, item) => {
          if (this.state.Selectcc) {
            // 已忽略
            return (
              <div className="zdyButtonA">
                <Button
                  icon="eye-invisible"
                  size="small"
                  onClick={() => {
                    this.iose(item);
                  }}
                  type="primary"
                >
                  恢复
                </Button>
              </div>
            );
          } else {
            return (
              <div className="zdyButtonA">
                <Button
                  icon="eye-invisible"
                  size="small"
                  onClick={() => {
                    this.iose(item);
                  }}
                  type="primary"
                >
                  忽略
                </Button>
              </div>
            );
          }
        },
      },
    ];
    return (
      <Suspense fallback={<PageLoading />}>
        <div>
          <div className={styles.toptit}>
            {this.state.Selectcc ? (
              <div className="zdyButtonA">
                <Button
                  onClick={this.allIgnore}
                  type="primary"
                  icon="eye-invisible"
                  loading={this.state.logines}
                >
                  全部恢复
                </Button>
              </div>
            ) : (
              <div className="zdyButtonA">
                <Button
                  onClick={this.allIgnore}
                  type="primary"
                  icon="eye-invisible"
                  loading={this.state.logines}
                >
                  全部忽略
                </Button>
              </div>
            )}
            <div>
              {getFieldDecorator('coreword1', {
                initialValue: this.state.Selectpd,
              })(
                <Select style={{ width: 120 }} onChange={this.SelectValue}>
                  <Option value="false">未忽略</Option>
                  <Option value="true">已忽略</Option>
                </Select>
              )}
              <span>&#12288;</span>
              {getFieldDecorator('coreword2', {
                initialValue: '',
              })(
                <Search
                  placeholder="多个关键词用空格隔开"
                  onSearch={value => {
                    this.setState({ searchKeys: value, page: 1 }, () => {
                      const { Selectcc, pageSize, page, searchKeys } = this.state;
                      this.similarAskList(Selectcc, pageSize, page, searchKeys);
                    });
                  }}
                  style={{ width: 324 }}
                />
              )}
            </div>
          </div>
          <Spin spinning={this.state.login}>
            <Table
              className="zdyTable"
              style={{ padding: '20px 0px 0px 0px' }}
              columns={columns}
              dataSource={this.state.similarList} // 数据
              // onChange={this.handleChange}
              pagination={{
                // 分页
                total: this.state.totala,
                pageSize: this.state.pageSize, // 显示几条一页
                current: this.state.page, // 当前页
                showSizeChanger: true, // 是否显示可以设置几条一页的选项
                showQuickJumper: true,
                onChange: this.pageWay,
                onShowSizeChange: this.onShowSizepageWay,
              }}
            />
          </Spin>
          <StandardToAsk
            onRef={ref => (this.StandardToAsk = ref)}
            delSimilarAsk={this.delSimilarAsk}
            append={this.append}
          />
        </div>
      </Suspense>
    );
  }
}

export default connect(({ user }) => ({
  // 全局数据
  currentUser: user.currentUser,
}))(Form.create()(SimilarAsk));
